<!-- App.vue -->
<template>
  <div id="app" class="font-inter bg-white text-gray-800 min-h-screen">

    <!-- 扫码弹窗 -->
    <el-dialog :visible.sync="showScanPopup" width="90%" :show-close="false" :modal-append-to-body="false" center
      custom-class="beauty-dialog" class="unsetStyle max700" @before-close="a()" :close-on-press-escape="false"
      :close-on-click-modal="false">
      <div class="scan-popup-content bg-white rounded-lg flex items-center relative">
        <div class="login-left-bg" :style="{
          background: 'url(' + appData.image.bg + ')',
          backgroundRepeat: 'no-repeat',
          backgroundSize: '100% 100%'
        }">
          <img style="max-width:150px;position:absolute;top:-20px;left:-20px;" :src="appData.image.topIcon" alt="">
        </div>
        <div class="relative z-10 p-8 " style="">
          <h2 class="text-2xl font-semibold mb-6 text-center text-primary pb20">{{ appData.title }}</h2>
          <div class="w-48 h-48 mx-auto bg-white flex items-center justify-center mb-6 rounded-xl shadow-lg">
            <!-- 这里应该是实际的二维码图片 -->
            <div class="bg-gray-100 border-2 border-dashed rounded-xl w-40 h-40 flex items-center justify-center">
              <div class="text-gray-400">

                <QrCode :url="qrUrl" title="" :isDown="false" :isEdit="false" @edit="" />

              </div>
            </div>
          </div>
          <p class="text-center pt25 text-sm text-gray-600 mb-6">{{ appData.qrcodeText }}</p>
          <button
            class="bg-primary text-white px-6 py-3 rounded-full w-full font-medium hover:bg-opacity-90 transition-all duration-300 shadow-md">{{
              appData.btnText }}</button>
        </div>
      </div>
    </el-dialog>



    <!-- <Header /> -->
    <!-- <main class="pt-16 pb-20"> -->
    <main class="pb-20" ref="scrollContainer">
      <el-carousel height="70vw" style="max-height: 800px;">
        <el-carousel-item v-for="item in bannerImage" :key="item">
          <img :src="item" alt="">
        </el-carousel-item>
      </el-carousel>
      <CategoryTabs @category-changed="clickCategory" />
      <!-- 推荐-信息流 -->
      <div v-if="category.label == '推荐'" class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4"
        style="align-items: start;">
        <AppCard v-for="(post, index) in AppCardData" :key="index" :post="post" @like="handleLike(index)"
          @collect="handleCollect(index)" @toUrl="toUrl('/mr/AppInfo?type=app&id=' + post.id)" class="postcard mt-6" />
      </div>

      <!-- 真实反馈-信息流 -->
      <div v-if="category.label == '真实反馈'" class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4"
        style="align-items: start;">
        <CaseCard v-for="(post, index) in CaseCardData" :key="index" :post="post" @like="handleLike(index)"
          @collect="handleCollect(index)" @toUrl="toUrl('/mr/AppInfo?type=case&id=' + post.id)" class="postcard mt-6" />
      </div>

      <div v-if="category.label != '真实反馈' && category.label != '推荐'"
        class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4" style="align-items: start;">
        <CaseCard v-for="(post, index) in WenCardData" :key="index" :post="post" @like="handleLike(index)"
          @collect="handleCollect(index)" @toUrl="toUrl('/mr/AppInfo?type=article&id=' + post.id)"
          class="postcard mt-6" />
      </div>

      <!-- 加载更多 -->
      <div class="py-6 text-center" v-if="category.label != '推荐' && !isNotData">
        <button
          class="px-6 py-2 bg-gray-light text-gray-dark rounded-full text-sm hover:bg-gray-medium transition-colors"
          @click="loadMoreContent" :disabled="isLoading">
          <span v-if="isLoading">加载中... <i class="fa fa-spinner fa-spin ml-1"></i></span>
          <span v-else>加载更多 <i class="fa fa-refresh ml-1"></i></span>
        </button>
      </div>
    </main>
    <Footer />
  </div>
</template>

<script>
import Header from './components/Header.vue'
import CategoryTabs from './components/CategoryTabs.vue'
import AppCard from './components/AppCard.vue'
import CaseCard from './components/CaseCard.vue'
import Footer from './components/Footer.vue'
import QrCode from "./components/QrCode.vue"


import { listBanner } from "@/api/demo/banner"; // 导入轮播图API
import { listCover } from "@/api/demo/cover"; // 导入封面API
import { listLibraryNoScope } from "@/api/demo/library"; // 导入案例库API
import { listArticle } from "@/api/demo/article"; // 导入文章API
import { generateCustomerQueryTemp, bindCustomerQuery, getCustomerByOpenId, getCustomerDesc, getCustomerDescOld } from "@/api/demo/customer";  // 导入用户信息API
import regionData from '@/utils/regionData'; // 导入地区数据
import { getConfigKey } from '@/api/system/config' // 导入配置API
import { getManageKey } from "@/api/demo/management";

import { getInfo } from "@/api/login";


export default {
  name: 'App',
  components: {
    Header,
    CategoryTabs,
    AppCard,
    CaseCard,
    Footer,
    QrCode
  },
  data() {
    return {
      showScanPopup: false,
      isLoading: false,
      baseApi: process.env.VUE_APP_BASE_API,
      appId: '',
      bannerImage: [require('@/assets/images/mr/banner.jpg')],
      category: { id: 0, label: "推荐" },
      regionOptions: regionData, // 添加地区数据

      AppCardData: [],
      pageNCover: 1,
      totalCover: 0,
      CaseCardData: [],
      pageNCase: 1,
      totalCase: 0,
      WenCardData: [],
      pageNWen: 1,
      totalWen: 0,
      pageSize: 10,
      isNotData: false,

      posts: [],
      qrUrl: '',
      user: null,
      setTimer: null,
      tempToken: null,

      appData: {
        "title": "扫码开启美丽之旅",
        "qrcodeText": "请使用【微信】扫描二维码，获取个性化美容建议",
        "btnText": "扫码立即体验",
        "image": {
          "bg": require('@/assets/images/mr/login.jpg'),
          "topIcon": require('@/assets/images/mr/100.png'),
        }
      }



    }
  },
  created() {
    getInfo().then((res) => {
      this.user = res.user
      console.log("用户信息：", res);
      this.init()
    });
  },
  mounted() {
    // 监听容器的scroll事件（加防抖）
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    // 移除容器的滚动监听
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    init() {


      if (!localStorage.getItem('openId')) {
        this.showScanPopup = true
      }
      if (!this.user.deptId) {
        this.$message.error("请先完善用户或绑定门店信息")
        this.$route.push('/index')
        return
      }
      this.getBannerImage()
      // 获取临时凭证后生成二维码
      generateCustomerQueryTemp({ deptId: this.user.deptId }).then((res) => {
        this.tempToken = res.tempToken  // tempToken
        this.getQrCode('&userId=' + this.user.userId + '&deptId=' + this.user.deptId + "&tempToken=" + this.tempToken)
      })

      this.getData()

      // 商户自己的配置
      getManageKey('sys.index.app.data').then(response => {
        if (response.code == 200 && response.rows && response.rows.length > 0) {
          const data = JSON.parse(response.rows[0].value) ? JSON.parse(response.rows[0].value) : null

          if (data) {
            if (data.image && data.image.bg && data.image.bg.length > 10) {
              data.image.bg = this.baseApi + data.image.bg
            } else {
              data.image.bg = require('@/assets/images/mr/login.jpg')
            }
            if (data.image && data.image.topIcon && data.image.topIcon.length > 10) {
              data.image.topIcon = this.baseApi + data.image.topIcon
            } else {
              data.image.topIcon = require('@/assets/images/mr/100.png')
            }
            this.appData = data
          }
        }
      });

      // 系统管理员配置的公众号信息
      getConfigKey('wx.appId').then(response => {
        this.appId = response.msg ? response.msg : ""

        if (!this.appId || this.appId == '') {
          this.$message.error('未配置微信AppID，请在系统配置中设置wx.appId')
        } else {
          console.log("this.appId", this.appId)
          this.setTimer = setInterval(() => {
            this.setOpenLocal()
          }, 1500)
        }
      });


    },
    getData() {
      if (this.category.id == 0 && this.category.label == '推荐') {
        console.log("推荐")
        listCover({ pageNum: this.pageNCover, pageSize: 10 }).then(response => {
          let AppCardData = []
          if (response.rows.length == 0) {
            this.isNotData = true
          }
          this.totalCover = response.total
          response.rows.forEach(post => {
            AppCardData.push({
              id: post.id,
              imageUrl: this.baseApi + post.image,
              subTitle: post.subtitleTitle,
              // content: post.content,
            })
          })
          console.log(this.totalCover, (this.AppCardData.length + AppCardData.length))


          if (this.totalCover >= (this.AppCardData.length + AppCardData.length)) {
            this.AppCardData.push(...AppCardData)
          } else {
            this.isNotData = true
          }
          this.isLoading = false
          console.log("AppCardData", this.AppCardData)

        })
      } else if (this.category.id == 0 && this.category.label == '真实反馈') {
        listLibraryNoScope({ pageNum: this.pageNCase, pageSize: 10 }).then(response => {
          let CaseCardData = []
          if (response.rows.length == 0) {
            this.isNotData = true
          }
          this.totalCase = response.total
          // console.log("response", this.pageNMaxCase)
          response.rows.forEach(post => {
            // console.log("post",post.publishAddress)
            CaseCardData.push({
              id: post.id,
              imageUrl: this.baseApi + post.imageUrl,
              title: post.title,
              content: post.content,
              location: this.formatRegionDisplay(post.publishAddress),
              likes: post.likes,
              comments: post.comments,
              collects: post.collects,
              likes: post.likes,
            })

          })
          console.log(this.totalCase, (this.CaseCardData.length + CaseCardData.length))

          if (this.totalCase >= (this.CaseCardData.length + CaseCardData.length)) {
            this.CaseCardData.push(...CaseCardData)
          } else {
            this.isNotData = true
          }
          this.isLoading = false
          console.log("CaseCardData", this.CaseCardData)
        })
      } else if (this.category.id > 0) {
        listArticle({ labelIds: this.category.id, pageNum: this.pageNCover, pageSize: 10 }).then(response => {
          let WenCardData = []
          if (response.rows.length == 0) {
            this.isNotData = true
          }
          this.totalWen = response.total
          response.rows.forEach(post => {
            WenCardData.push({
              id: post.id,
              imageUrl: this.baseApi + post.image,
              title: post.title,
              content: post.content,
              likes: post.likes,
              comments: post.comments,
              collects: post.collects,
              likes: post.likes,
            })
          })
          console.log(this.totalWen, (this.WenCardData.length + WenCardData.length))

          if (this.totalWen >= (this.WenCardData.length + WenCardData.length)) {
            this.WenCardData.push(...WenCardData)
          } else {
            this.isNotData = true
          }
          this.isLoading = false

        })
      }

    },
    getQrCode(queryStr = "") {
      console.log("getQrCode!!!!!：：this.$store.state.user", this.user)
      this.qrUrl = window.location.origin + '/wechat/getWxInfo?backPage=/wechat/backStop' + queryStr
      console.log("qrUrl", this.qrUrl);
    },
    setOpenLocal() {
      if (localStorage.getItem('openId')) {
        console.log("已设置openId-终止")
        clearInterval(this.setTimer)
        return
      }
      getCustomerDescOld({ tempToken: this.tempToken, userId: this.user.userId, deptId: this.user.deptId }).then(res => {
        // console.log("res", res)
        if (res && res.code == 200) {
          this.showScanPopup = false
          const data = res.data
          localStorage.setItem('CustomerInfo', JSON.stringify(data))
          localStorage.setItem('openId', data.openId)
          localStorage.setItem('deptId', data.deptId)
          console.log(this.setTimer)
          clearInterval(this.setTimer)
          console.log(this.setTimer)
        } else if (res && res.code == 500) {
          // 超过时限，重新进入页面
          // this.$message.error("二维码已过期，请重新扫码")
          window.location.reload()
          return
        } else {
          this.showScanPopup = true
        }
      });
      // getCustomerDesc({ tempToken: this.tempToken }).then(res => {
      //   // console.log("res", res)
      //   if (res && res.code == 200) {
      //     this.showScanPopup = false
      //     const data = res.data
      //     localStorage.setItem('CustomerInfo', JSON.stringify(data))
      //     localStorage.setItem('openId', data.openId)
      //     localStorage.setItem('deptId', data.deptId)
      //     console.log(this.setTimer)
      //     clearInterval(this.setTimer)
      //     console.log(this.setTimer)
      //   } else {
      //     this.showScanPopup = true

      //   }
      // });
    },
    setOpen() {

      // console.log(window.location.origin+this.baseApi+'/wechat/userInfo?deptId=101&code=djksnvfulnvfdfdsavfd')
      // console.log(process.env.VUE_APP_APPID, process.env.VUE_APP_BASE_API)
      console.log(this.$route.query)
      const openStr = this.$route.query.open
      let deptId = this.$route.query.deptId
      deptId = (deptId && deptId != 'null') ? deptId : 100
      if (openStr && openStr !== 'null' && openStr !== 'undefined' && openStr !== '') {
        localStorage.setItem('openId', openStr)
        localStorage.setItem('deptId', deptId)
        getCustomerByOpenId({ openId: openStr, deptId: deptId }).then(res => {
          if (res.code == 200) {
            localStorage.setItem('CustomerInfo', JSON.stringify(res.data))
          }
        });
      } else {
        // 没有参数openId、没有cookie，则获取微信授权
        if (!localStorage.getItem('openId')) {
          // 获取微信授权
          const url =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
            this.appId +
            '&redirect_uri=' + window.location.origin + '%2Fmr%2Fwww%3FdeptId%3D' + deptId + '&response_type=code&scope=snsapi_userinfo&state=STATE'
          console.log(url)

          window.location = url
        }
      }
    },

    getBannerImage() {
      // 获取轮播图
      listBanner().then(response => {
        let bannerImage = []
        response.rows.forEach(post => {
          bannerImage.push(this.baseApi + post.imageUrl)
        })
        this.bannerImage = bannerImage
      })
    },
    toUrl(url) {
      this.$router.push(url)
    },
    clickCategory(e) {
      console.log(e)
      this.category = e
      this.getData()
      this.isNotData = false
    },

    handleLike(index) {
      const post = this.posts[index]
      post.hasLiked = !post.hasLiked

      // 更新点赞数
      let likeCount = parseFloat(post.likes)
      const hasK = post.likes.includes('k')

      if (hasK) {
        likeCount = likeCount * 1000
      }

      likeCount = post.hasLiked ? likeCount + 1 : likeCount - 1

      // 格式化点赞数显示
      if (likeCount >= 1000) {
        post.likes = (likeCount / 1000).toFixed(1) + 'k'
      } else {
        post.likes = likeCount.toString()
      }
    },
    handleCollect(index) {
      const post = this.posts[index]
      post.hasCollected = !post.hasCollected
    },
    handleScroll() {
      console.log(window.innerHeight, window.scrollY, document.body.offsetHeight)
      // if (this.isLoading || this.list.length >= this.total) return;

      if (this.isLoading || this.isNotData) return

      // 当滚动到页面底部附近时加载更多
      if (window.scrollY >= document.body.offsetHeight - 200) {
        // console.log("loadMoreContent")
        this.loadMoreContent()
      }
    },
    loadMoreContent() {
      this.isLoading = true

      if (this.category.label == '推荐') {
        console.log("this.pageNCover", this.pageNCover, this.pageNMaxCover)
        if (this.totalCover >= this.AppCardData.length) {
          this.pageNCover += 1
        } else {
          console.log("没有更多数据了")
          this.isNotData = true
          this.isLoading = false
          return
        }
      } else if (this.category.label == '真实反馈') {

        if (this.totalCase >= this.CaseCardData.length) {
          this.pageNCase += 1
        } else {
          console.log("没有更多数据了", this.totalCase, this.CaseCardData.length)
          this.isNotData = true
          this.isLoading = false
          return
        }

      } else if (this.category.id > 0) {
        if (this.totalWen >= this.WenCardData.length) {
          this.pageNWen += 1
        } else {
          console.log("没有更多数据了")
          this.isNotData = true
          this.isLoading = false
          return
        }
      }
      this.getData()
    },
    /** 格式化区域显示 */
    formatRegionDisplay(region) {
      if (!region) return '-';

      try {
        // 如果region是字符串，尝试解析为数组
        let regionArray = region;
        if (typeof region === 'string') {
          regionArray = JSON.parse(region);
        }

        // 处理二维数组格式 [["140000","140100","140105"],["140000","140100","140106"]]
        if (Array.isArray(regionArray) && regionArray.length > 0) {
          // 判断是否是二维数组
          if (Array.isArray(regionArray[0])) {
            // 处理多个地区路径
            const regionNames = regionArray.map(path => {
              return this.getFullRegionName(path);
            });

            // 如果所有路径都相同（只显示一个），或者显示前几个用逗号分隔
            const uniqueNames = [...new Set(regionNames)];
            if (uniqueNames.length === 1) {
              return uniqueNames[0];
            } else {
              // 显示前3个，超过用等表示
              const displayNames = uniqueNames.slice(0, 3);
              return displayNames.join('、') + (uniqueNames.length > 3 ? ` 等${uniqueNames.length}个地区` : '');
            }
          } else {
            // 处理单个地区路径（一维数组）
            return this.getFullRegionName(regionArray);
          }
        }
        return '-';
      } catch (e) {
        console.error('区域数据解析失败:', e);
        // 如果解析失败，返回原始值
        return region || '-';
      }
    },
    /** 获取完整的地区名称 */
    getFullRegionName(codes) {
      if (!codes || !Array.isArray(codes) || codes.length === 0) return '';

      const names = [];
      let currentLevel = this.regionOptions;

      for (let i = 0; i < codes.length; i++) {
        const code = codes[i];
        const region = currentLevel.find(item => item.value === code);
        if (region) {
          names.push(region.label);
          currentLevel = region.children || [];
        } else {
          // 如果没有找到对应的地区，尝试直接使用编码
          names.push(code);
          break;
        }
      }

      return names.join(' / ');
    },

  }
}
</script>

<style scoped>
@media (min-width: 1500px) {
  #app {
    max-width: 1000px;
    margin: 0 auto;
  }
}

/* 全局样式保持不变 */
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }

  .scrollbar-hide {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }

  a .scrollbar-hide::-webkit-scrollbar {
    display: none;
  }

  .text-shadow {
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  }

  .card-hover {
    transition: transform 0.2s ease;
  }

  .card-hover:hover {
    transform: translateY(-2px);
  }
}

.postcard {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 15px;
  overflow: hidden;
  align-self: start;
}

.max700 {
  max-width: 700px !important;
}

/* // 扫码弹窗样式 */
.scan-popup-content {
  position: relative;
  border-radius: 10px;
}

.login-left-bg {
  width: 260px;
  height: 500px;
  border-radius: 10px;
}

.bg-primary {
  background-color: #8a5a52;
}

.text-primary {
  color: #8a5a52;
}

.green {
  color: #22c55e;
  font-weight: bold;
}

@media (max-width:600px) {
  .login-left-bg {
    display: none;
  }
}
</style>